import * as echarts from 'echarts'

// 防抖函数
export function debounce(func, wait, immediate = false) {
  let timeout
  return function executedFunction() {
    const context = this
    const args = arguments
    
    const later = function() {
      timeout = null
      if (!immediate) func.apply(context, args)
    }

    const callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) func.apply(context, args)
  }
}

// 节流函数
export function throttle(func, limit) {
  let inThrottle
  return function() {
    const args = arguments
    const context = this
    if (!inThrottle) {
      func.apply(context, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

// 格式化数字
export function formatNumber(num, digits = 2) {
  return Number(num).toFixed(digits)
}

// 计算BMI
export function calculateBMI(weight, height) {
  if (!weight || !height) return 0
  const heightInMeters = height / 100
  return (weight / (heightInMeters * heightInMeters)).toFixed(1)
}

// 获取BMI状态
export function getBMIStatus(bmi) {
  if (bmi < 18.5) return { text: '偏瘦', type: 'warning' }
  if (bmi < 24) return { text: '正常', type: 'success' }
  if (bmi < 28) return { text: '超重', type: 'warning' }
  return { text: '肥胖', type: 'danger' }
}

// 计算基础代谢率（BMR）
export function calculateBMR(weight, height, age, gender) {
  if (gender === 'male') {
    return 66 + (13.7 * weight) + (5 * height) - (6.8 * age)
  } else {
    return 655 + (9.6 * weight) + (1.8 * height) - (4.7 * age)
  }
}

// 计算每日消耗热量（TDEE）
export function calculateTDEE(bmr, activityLevel) {
  const activityFactors = {
    sedentary: 1.2,
    lightly_active: 1.375,
    moderately_active: 1.55,
    very_active: 1.725,
    extra_active: 1.9
  }
  return Math.round(bmr * activityFactors[activityLevel])
}

// 计算推荐营养摄入
export function calculateNutrition(tdee, goal) {
  let calories = tdee
  switch (goal) {
    case 'lose_weight':
      calories = tdee - 500 // 每天减少500卡路里
      break
    case 'gain_muscle':
      calories = tdee + 300 // 每天增加300卡路里
      break
  }

  return {
    calories,
    protein: Math.round((calories * 0.3) / 4), // 30%蛋白质
    carbs: Math.round((calories * 0.5) / 4),   // 50%碳水
    fat: Math.round((calories * 0.2) / 9)      // 20%脂肪
  }
}

// 生成图表渐变色
export function getGradientColor(color, opacity = 0.3) {
  return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    { offset: 0, color: color },
    { offset: 1, color: color.replace(')', `, ${opacity})`) }
  ])
} 